/*
 * Copyright (c) 2016. For Intelligent Group.
 */

package com.intelligent.ispc.core.service.impl;

import com.intelligent.ispc.cache.UserDataCacheFactory;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.common.utils.ResourceBundleUtils;
import com.intelligent.ispc.core.entity.Role;
import com.intelligent.ispc.core.repository.RoleDao;
import com.intelligent.ispc.core.repository.UserDao;
import com.intelligent.ispc.core.dto.UserDto;
import com.intelligent.ispc.core.entity.User;
import com.intelligent.ispc.core.service.SecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Peter on 2016/7/11.
 */
@Service
public class SecurityServiceImpl implements SecurityService {

    private final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

    @Autowired
    protected UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDataCacheFactory userDataCacheFactory;

    @Override
    public UserDto findByLoginName(String loginName) {
        userDataCacheFactory.getCacheUserData().invalidateAll();
        User user = userDao.findByLoginName(loginName);

        if (user == null) {
            throw new ApplicationException(ExceptionMessages.ERR_15007, ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_OBJECT_INVALID));
        }

        UserDto dto = new UserDto();
        try {
            BeanUtils.copyProperties(user, dto);
            userDataCacheFactory.getCacheUserData().get(loginName);
        } catch (Exception ex) {
            throw new ApplicationException(ex);
        }
        return dto;
    }

    @Override
    public List<Long> findRoleByUserId(Long userid) {
        if (userid == null) {
            throw new ApplicationException(ExceptionMessages.ERR_14001, ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_CONFIG_PARAMETER_INVALID));
        }

        List<Long> roles = userDao.findRoleByUserId(userid);
        return roles;
    }

    @Override
    public List<Role> findRolesByIds(List<Long> roles) {
        if (roles == null || roles.size() == 0) {
            throw new ApplicationException(ExceptionMessages.ERR_14001, ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_CONFIG_PARAMETER_INVALID));
        }

        return roleDao.findByIds(roles);
    }

    @Override
    public  void updateUserPwdByUserDto(UserDto userDto) {

        User user = new User();
        try {
            BeanUtils.copyProperties(userDto, user);
            userDao.updateByUserId(user);
        } catch (Exception ex) {
            throw new ApplicationException(ex);
        }
    }
}
